<template>
  <view class="return-detail-page">
    
    <!-- 退库单信息卡片 -->
    <view class="info-card">
      <view class="card-header">
        <view class="header-row">
          <view class="label-box">退库单号</view>
          <text class="code-text">{{ returnInfo.code }}</text>
        </view>
        <text class="title-text">{{ returnInfo.returnOrderName || '未命名退库单' }}</text>
      </view>
      
      <u-line length="100%" margin="20rpx 0"></u-line>
      
      <view class="info-section">
        <view class="info-row">
          <text class="info-label">退库人</text>
          <text class="info-value">{{ returnInfo.returnPerson }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">退库日期</text>
          <text class="info-value">{{ returnInfo.returnDate }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">退库存放位置</text>
          <text class="info-value">{{ returnInfo.returnLocation }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">备注</text>
          <text class="info-value">{{ returnInfo.remark || '无' }}</text>
        </view>
      </view>
    </view>
    
    <!-- 资产列表 -->
    <view class="asset-section">
      <view class="section-header">
        <text class="section-title">资产列表</text>
        <text class="asset-count">共计: {{ returnInfo.assets?.length || 0 }}</text>
      </view>
      
      <view class="asset-list" v-if="returnInfo.assets && returnInfo.assets.length > 0">
        <view class="asset-item" v-for="(item, index) in returnInfo.assets" :key="index">
          <view class="asset-img-container">
            <image 
              class="asset-img" 
              :src="item.image ? `${BASE_URL}/File/GetImage?fileId=${item.image}` : '/static/placeholder.png'" 
              mode="aspectFill" 
            />
          </view>
          <view class="asset-info">
            <view class="asset-name">{{ item.name }}</view>
            <view class="asset-detail">资产分类: {{ item.category }}</view>
            <view class="asset-detail">资产编码: {{ item.code }}</view>
            <view class="asset-detail">资产规格: {{ item.spec }}</view>
            <view class="asset-detail">存放地点: {{ item.location }}</view>
          </view>
        </view>
      </view>
      <view class="empty-tip" v-else>
        <text>暂无资产</text>
      </view>
    </view>
    
    <!-- 普通模式下的底部按钮 -->
    <view class="footer-btn" v-if="!isAuditMode">
      <view class="btn-group">
        <view class="btn back-btn" @click="goBack">返回</view>
      </view>
    </view>
    
    <!-- 审核模式下的底部按钮 -->
    <view class="footer-btn audit-btns" v-if="isAuditMode">
      <up-button type="default" text="驳回" @click="showRejectDialog"></up-button>
      <up-button type="primary" text="通过" @click="approveReturn"></up-button>
    </view>
    
    <!-- 驳回原因弹窗 -->
    <up-popup :show="showRejectPopup" :round="10" mode="center" @close="closeRejectDialog" @open="onRejectPopupOpen">
      <view class="reject-popup">
        <view class="reject-title">驳回原因</view>
        <view class="reject-content">
          <up-textarea
            v-model="rejectReason"
            placeholder="请输入驳回原因"
            :maxlength="200"
          ></up-textarea>
        </view>
        <view class="reject-buttons">
          <up-button type="default" text="取消" @click="closeRejectDialog"></up-button>
          <up-button type="primary" text="确定" @click="confirmReject"></up-button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import http, { BASE_URL } from "@/api/request";
import { t } from "@/locale/index.js"

// 退库单信息
const returnInfo = ref({
  code: '',
  returnOrderName: '',
  returnPerson: '',
  returnDate: '',
  returnLocation: '',
  remark: '',
  assets: []
});

// 审核相关状态
const isAuditMode = ref(false);
const showRejectPopup = ref(false);
const rejectReason = ref('');
const pageParams = ref({
  returnCode: '',
  mode: ''
});

onLoad((options) => {
  // 保存页面参数
  pageParams.value = {
    returnCode: options.returnCode || '',
    mode: options.mode || ''
  };
  
  // 判断是否为审核模式
  isAuditMode.value = options.mode === 'audit';
//   console.log('是否为审核模式:', isAuditMode.value);
  // 如果有退库单号，则获取详情
  if (options.returnCode) {
    getReturnDetail(options.returnCode);

  }
  if(isAuditMode.value){
    uni.setNavigationBarTitle({
      title: t("assetReturn.audit")
    });
  }else{
    uni.setNavigationBarTitle({
      title: t("assetReturn.detail")
    });
  }
});

// 获取退库单详情
const getReturnDetail = (returnCode) => {
  // 显示加载中
  uni.showLoading({
    title: '加载中...'
  });
  
  // 构建请求参数
  const data = { 
    "pageCode": "assetreturn", 
    "params": { 
      "args": [ 
        { 
          "name": "interfaceCode", 
          "value": "assetreturn.getAssetReturnOrderDetail" 
        }, 
        { 
          "name": "assetReturnCode", 
          "value": returnCode 
        } 
      ] 
    }, 
    "methodName": "getAssetReturnOrderDetail" 
  };
  
  // 调用接口
  http.post("/api/module/Invoke", data).then((res) => {
    uni.hideLoading();
    
    if (res.isSuccess && res.result) {
      // 获取主单据信息和资产列表
      const masterInfo = res.result.masterInfo || {};
      const assetList = res.result.assetDetails || [];
      
      // 更新退库信息
      returnInfo.value = {
        code: masterInfo.returnCode || returnCode,
        returnOrderName: masterInfo.returnName || '',
        returnPerson: masterInfo.returnUserName || '',
        returnDate: masterInfo.fReturnDate?.split(' ')[0] || '',
        returnLocation: masterInfo.returnLocationName || masterInfo.returnLocation || '',
        remark: masterInfo.remark || '',
        stateName: masterInfo.returnStateName || '未知状态',
        // 处理资产列表
        assets: assetList.map(asset => ({
          id: asset.id,
          name: asset.assetName,
          category: asset.assetClassName,
          code: asset.assetCode,
          spec: asset.specModel,
          location: asset.storageLocation,
          image: asset.image
        }))
      };
    } else {
      uni.showToast({
        title: res.error || '获取详情失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    uni.hideLoading();
    console.error('获取退库详情失败:', err);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 显示驳回原因弹窗
const showRejectDialog = () => {
  rejectReason.value = '';
  showRejectPopup.value = true;
};

// 关闭驳回原因弹窗
const closeRejectDialog = () => {
  showRejectPopup.value = false;
};

// 弹窗打开事件
const onRejectPopupOpen = () => {
  console.log('驳回弹窗已打开');
};

// 确认驳回
const confirmReject = () => {
  if (!rejectReason.value.trim()) {
    uni.showToast({
      title: '请输入驳回原因',
      icon: 'none'
    });
    return;
  }
  rejectReturn();
  closeRejectDialog();
};

// 审核通过
const approveReturn = () => {
  uni.showModal({
    title: '审核确认',
    content: `确定通过退库单 ${pageParams.value.returnCode} 的审核吗？`,
    cancelText: '取消',
    confirmText: '确定',
    success: (res) => {
      if (res.confirm) {
        // 调用审核通过接口
        submitAudit('APPROVED');
      }
    }
  });
};

// 驳回退库单
const rejectReturn = () => {
  // 调用驳回接口
  submitAudit('REJECTED');
};

// 提交审核结果
const submitAudit = (auditResult) => {
  uni.showLoading({
    title: '提交中...'
  });
  
  const data = { 
    pageCode: "assetreturn", 
    params: { 
      args: [ 
        { 
          name: "interfaceCode", 
          value: "assetreturn.approveAssetReturnOrder" 
        }, 
        { 
          name: "assetReturnCode", 
          value: pageParams.value.returnCode
        },
        {
          name: "auditState",
          value: auditResult
        },
        {
          name: "approvalReason",
          value: auditResult === 'REJECTED' ? rejectReason.value : ''
        }
      ] 
    }, 
    methodName: "approveAssetReturnOrder" 
  };
  
  http.post("/api/module/Invoke", data).then((res) => {
    uni.hideLoading();
    if (res.isSuccess) {
      uni.showToast({
        title: auditResult === 'APPROVED' ? '审核通过成功' : '驳回成功',
        icon: 'success'
      });
      
      // 触发列表页面数据刷新
      uni.$emit('data-changed');
      
      // 延迟返回，确保提示信息显示完成
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: res.error || '操作失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    uni.hideLoading();
    console.error('审核操作失败:', err);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  });
};
</script>

<style lang="scss" scoped>
.return-detail-page {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.info-card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  margin-bottom: 20rpx;
}

.header-row {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.label-box {
  background-color: #4792FD;
  color: #fff;
  padding: 8rpx 16rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  margin-right: 20rpx;
}

.code-text {
  font-size: 28rpx;
  color: #666;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.info-section {
  margin-top: 20rpx;
}

.info-row {
  display: flex;
  margin-bottom: 20rpx;
}

.info-label {
  width: 200rpx;
  color: #666;
  font-size: 28rpx;
}

.info-value {
  flex: 1;
  color: #333;
  font-size: 28rpx;
}

.asset-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 120rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.asset-count {
  font-size: 26rpx;
  color: #999;
}

.asset-list {
  margin-top: 20rpx;
}

.asset-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
}

.asset-img-container {
  width: 120rpx;
  height: 120rpx;
  margin-right: 20rpx;
}

.asset-img {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
  background-color: #f0f0f0;
}

.asset-info {
  flex: 1;
}

.asset-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.asset-detail {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 6rpx;
}

.empty-tip {
  text-align: center;
  padding: 60rpx 0;
  color: #999;
  font-size: 28rpx;
}

.footer-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.btn-group {
  display: flex;
  justify-content: center;
}

.btn {
  width: 200rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 40rpx;
  font-size: 28rpx;
  margin: 0 20rpx;
}

.back-btn {
  background-color: #4792FD;
  color: #fff;
}

/* 审核模式下的按钮样式 */
.audit-btns {
  display: flex;
  justify-content: space-around;
}

/* 驳回弹窗样式 */
.reject-popup {
  width: 600rpx;
  padding: 30rpx;
}

.reject-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.reject-content {
  margin-bottom: 30rpx;
}

.reject-buttons {
  display: flex;
  justify-content: space-between;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #4792FD;
  color: #fff;
}
</style>
